package com.leyou.search.service.impl;

import com.leyou.commons.dto.PageDTO;
import com.leyou.commons.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.dto.SearchParamDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.entity.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.ml.job.results.Bucket;
import org.elasticsearch.index.mapper.ObjectMapper;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import static com.leyou.search.constants.SearchConstants.*;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private ItemClient itemClient;

    @Override
    public void createIndexAndMapping() {
        // 删除已经存在的索引库
        try {
            goodsRepository.deleteIndex();
        } catch (Exception e) {
            log.error("删除失败，可能索引库不存在！", e);
        }
        // 然后创建一个新的
        goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }

    @Override
    public void loadData() {
        int page = 1, rows = 100;
        while (true) {
            log.info("开始导入第{}页数据", page);
            // 分页查询已经上架的spu
            PageDTO<SpuDTO> result = itemClient.querySpuByPage(page, rows, true, null, null, null);
            List<SpuDTO> list = result.getItems();

            // 遍历Spu集合，把SpuDTO通过buildGoods方法转为Goods
            List<Goods> goodsList = list.stream()
                    .map(this::buildGoods).collect(Collectors.toList());

            // 批量写入Elasticsearch
            goodsRepository.saveAll(goodsList);
            log.info("导入第{}页数据结束。", page);
            // 翻页
            page++;

            // 获取总页数
            Long totalPage = result.getTotalPage();
            // 判断是否还有spu没有查询
            if (page > totalPage) {
                // 没有则结束
                break;
            }
        }
    }

    private Goods buildGoods(SpuDTO spu) {
        // 1.自动补全的提示字段
        List<String> suggestion = new ArrayList<>(
                Arrays.asList(StringUtils.split(spu.getCategoryName(), "/")));
        suggestion.add(spu.getName());
        suggestion.add(spu.getBrandName());

        // 2.sku的价格集合
        // 2.1.查询sku集合
        List<SkuDTO> skuList = spu.getSkus();
        if (CollectionUtils.isEmpty(skuList)) {
            // 没有sku，我们去查询
            skuList = itemClient.querySkuBySpuId(spu.getId());
        }
        // 2.2.获取价格集合
        Set<Long> prices = skuList.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());

        // 3.商品销量
        long sold = skuList.stream().mapToLong(SkuDTO::getSold).sum();

        // 4.sku的某个图片
        String image = StringUtils.substringBefore(skuList.get(0).getImages(), ",");

        // 5.规格参数
        List<Map<String, Object>> specs = new ArrayList<>();
        // 5.1.查询规格参数name和value键值对，只查询参与搜索的
        List<SpecParamDTO> params = itemClient.querySpecsValues(spu.getId(), true);
        // 5.2.封装
        for (SpecParamDTO param : params) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("name", param.getName());
            map.put("value", chooseSegment(param));
            specs.add(map);
        }

        // 创建Goods对象，并封装数据
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        // 自动补全的提示字段
        goods.setSuggestion(suggestion);
        // 规格参数
        goods.setSpecs(specs);
        // 商品销量
        goods.setSold(sold);
        // 商品标题
        goods.setTitle(spu.getTitle() + StringUtils.join(suggestion, " "));
        // sku的价格集合
        goods.setPrices(prices);
        // sku的某个图片
        goods.setImage(image);
        goods.setCategoryId(spu.getCid3());
        goods.setBrandId(spu.getBrandId());
        goods.setId(spu.getId());
        return goods;
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 查询补全数据
     *
     * @param key
     * @return
     */
    @Override
    public Mono<List<String>> getSuggestion(String key) {
        if (StringUtils.isBlank(key)) {
            throw new LyException(400, "请求参数不能为空！");
        }
        return goodsRepository.suggestBySingleField(SUGGESTION_FIELD, key);
    }

    /**todo
     * 分页查询商品信息
     * @param searchParam
     * @return
     */
    @Override
    public Mono<PageInfo<Goods>> searchGoods(SearchParamDTO searchParam) {
        //构建查询条件的工厂对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //获取查询的条件
        QueryBuilder query = builderQuery(searchParam);
        //添加查询的一些条件
        sourceBuilder.query(query);
        //判断当前页是否为空或者小于0,重置到第一页
        Integer page = searchParam.getPage();
        if(null==page||page<=1){
            page=1;
        }
        //添加分页条件
        Integer from = (page-1)*searchParam.getSize();
        sourceBuilder.from(from);
        sourceBuilder.size(searchParam.getSize());
       //添加高亮条件
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<am>");
        highlightBuilder.postTags("</am>");
        sourceBuilder.highlighter(highlightBuilder);
        return goodsRepository.queryBySourceBuilderForPageHighlight(sourceBuilder);
    }
    //抽离出字段查询条件的方法
    private QueryBuilder builderQuery(SearchParamDTO searchParam) {
        //判断是否有查询字段
        String key = searchParam.getKey();
        if (StringUtils.isEmpty(key)){
            throw new LyException(400,"请求封装参数有误，查询key不能为空");
        }
        return QueryBuilders.matchQuery("title", key).operator(Operator.AND);
    }

    /**todo
     * 查询过滤条件规格参数
     * @param searchParam
     * @return
     */
    @Override
    public Mono<Map<String, ?>> listFilter(SearchParamDTO searchParam) {
        //构建查询条件的工厂对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //添加查询的条件
        sourceBuilder.query(builderQuery(searchParam));
        //对分类聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("categoryAgg").field("categoryId"));
        //对品牌聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("brandAgg").field("brandId"));
        //对规格参数聚合
        sourceBuilder.aggregation(
                        AggregationBuilders.nested("specAgg", "specs")
                        .subAggregation(AggregationBuilders.terms("nameAgg").field("specs.name")
                        .subAggregation(AggregationBuilders.terms("valueAgg").field("specs.value")))
        );
        Mono<Aggregations> aggregationsMono = goodsRepository.aggregationBySourceBuilder(sourceBuilder);
      return   aggregationsMono.map(aggregations -> {
            Map<String, List<?>> result = new LinkedHashMap<>();

            //获取分类对象集合
            Terms categoryAgg = aggregations.get("categoryAgg");
            List<Long> categoryIds = categoryAgg.getBuckets().stream()
                    .map(Terms.Bucket::getKeyAsNumber)
                    .map(Number::longValue)
                    .collect(Collectors.toList());
            //判断品牌id是否为空
            if (CollectionUtils.isEmpty(categoryIds)) {
                result.put("分类", new ArrayList<>());
            } else {
                result.put("分类", this.itemClient.queryCategoryByIds(categoryIds));
            }
            //获取品牌对象集合
            Terms brandAgg = aggregations.get("brandAgg");
            List<Long> brandIds = brandAgg.getBuckets().stream()
                    .map(Terms.Bucket::getKeyAsNumber)
                    .map(Number::longValue)
                    .collect(Collectors.toList());
            //判断品牌id是否为空
            if (CollectionUtils.isEmpty(brandIds)) {
                result.put("品牌", new ArrayList<>());
            } else {
                result.put("品牌", this.itemClient.queryBrandByIds(brandIds));
            }
            //获取规格参数集合
            Nested specAgg = aggregations.get("specAgg");
            Terms nameAgg = specAgg.getAggregations().get("nameAgg");
            nameAgg.getBuckets()
                    .stream()
                    .forEach(
                            bucket -> {
                                String key = ((Terms.Bucket) bucket).getKeyAsString();
                                Terms valueAgg = ((Terms.Bucket) bucket).getAggregations().get("valueAgg");
                                List<String> value = valueAgg.getBuckets().stream().map(Terms.Bucket::getKeyAsString)
                                        .collect(Collectors.toList());
                                result.put(key, value);
                            });
            return result;
        });
    }

    @Override
    public void saveGoodsById(Long spuId) {
        // 需要spu
        SpuDTO spu = itemClient.queryGoodsById(spuId);
        // 构建goods
        Goods goods = buildGoods(spu);
        // 写入索引库
        goodsRepository.save(goods);
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        goodsRepository.deleteById(spuId);
    }
}